package test.socket;
import java.io.*;
import java.net.Socket;

class ServerThread implements Runnable {
    private String name;
    private DataInputStream inputStream;
    private DataOutputStream outputStream;


    public ServerThread(Socket socket, String name) {
        this.name = name;
        try {
            inputStream =  new DataInputStream(socket.getInputStream());
            outputStream = new DataOutputStream(socket.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
          while (true) {
              receive();
          }


    }

    public void receive(){
        try {
            System.out.println("服务端开始接收!");
            System.out.println(inputStream==null);
            byte[] bys = new byte[1024];
            int len = 0;
            int length = inputStream.available();
            byte[] bys2 = new byte[length];
         /*   while ((len = inputStream.read(bys))!=-1){
                System.out.println("服务器接收："+new String(bys,0,len));
                System.out.println("fffffffffffffffffffffffff");

            }

         while (length!=0){
             inputStream.read(bys2);
             length = inputStream.available();
             System.out.println("exit~~~~~~~~~~~~~~~~~~~~```");

         }*/
            String  msg = inputStream.readUTF();
            inputStream.readUTF();
            System.out.println("服务端接收:"+msg);
            send();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public void  send() {
        System.out.println("服务器发送:你叫"+name+" 在线人数："+TcpServer.count);
        try {
            outputStream.writeUTF("你叫"+name+" 在线人数-->"+TcpServer.count);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
